#include "servercommandsendcodec.h"
#include <QFile>
#include "../../common/comiocontroller.h"
#include "../serverconmanager.h"
ServerCommandSendCodec::ServerCommandSendCodec(QObject *parent)
{
}

bool ServerCommandSendCodec::execute(QStringList args)
{
    qint64 llCodecSize = args.at(1).toLongLong();
    QString cstrFilename = args.at(2);
    ComIOController::getInstance()->msgOutput(QString("<ServerCommandSendCodec>:File name is %1, File size is %2 Byte").arg(cstrFilename).arg(llCodecSize), MSG_DEBUG);
    ServerConManager* pcConManager = ServerConManager::getInstance();
    //read & save the codec from socket
    //open new file
    QFile cCodecFile(cstrFilename);
    if( cCodecFile.open(QIODevice::WriteOnly) == false ) {
        ComIOController::getInstance()->msgOutput("<ServerCommandSendCodec>:Create codec file failure.", MSG_ERROR);
        return false;
    }
    qint64 llRemainingSize = llCodecSize;
    qint64 llNextReadSize = 64*1024;
    while( llRemainingSize > 0 ) {
        ComIOController::getInstance()->msgOutput(QString("<ServerCommandSendCodec>:Remaining size %1.").arg(llRemainingSize), MSG_ERROR);
        if(llRemainingSize < llNextReadSize)
            llNextReadSize = llRemainingSize;
        QByteArray abReceived = pcConManager->m_cClients[0]->m_cTcpClient->read(llNextReadSize);
        llRemainingSize -= abReceived.size();
        if( cCodecFile.write(abReceived) != abReceived.size() ) {
            ComIOController::getInstance()->msgOutput("<ServerCommandSendCodec>:Write codec file failure.", MSG_ERROR);
            goto end;
        }
    }

end:
    //close file
    cCodecFile.close();
    return false;
}
